// pages/my_care/adv_cares.js
var Show = require("../../utils/alert/alert.js");
const date = new Date()
var app = getApp()
var that   
Page({ 
  data: { 
    index:0,   //房间数组的下标，相当与客户选择的房间数-1     
    array: [1],  //可入住的房间数量 
    index2: 0,   //猫咪数量数组下标， 
    array2: ['1只'],  //可选择的猫咪数量
    gg:false,
    gg2:false,//是否处于默认状态，显示请选择，
    actionSheetHidden:true,
    actionSheetHidden_cat:true,
    isclick_wx_pay:false,//是否点击微信支付显示微信支付界面，true为点击后要显示支付界面
    my_cat:null,
    startDate:null,
    endDate:null,
    d:null,//居住天数
    house_id:null,
    my_cat_care:[],//我的被选中托养的猫 
    pay_msg:null,

    house_name: "",
    house_price: "",
    live_num: "",
    vip_price:0,  //会员价
    agree:false,   //是否同意托养协议
    care_agree:null,  //托养协议内容
    adv_price:0,  //要预付的房费
    remark:'', //备注

    showModalStatus: false, //会员支付弹窗是否显示
    pwd: '',// 会员支付密码
    level: "",//0非会员1会员
    focus:false,//输入密码的input是否获得焦点出现键盘
  },
  onLoad: function (options) {
    that=this;
    that.setData({ care_agree: app.hotelData.house_notict.care_agree})
    if (options.startDate && options.endDate) {
      that.setData({ startDate: options.startDate, endDate: options.endDate, d: options.d, house_id: options.house_id});
    }
    that.set_house_msg(that.data.house_id)//根据房间类型设置房间信息
    that.get_room_num(that.data.startDate, that.data.endDate, that.data.house_id);  //获取当前日期范围内最多的房间数
    var openid = wx.getStorageSync('openid');
    app.req("get_cat.html", { sessionid: wx.getStorageSync('3rd_session'), "openid": openid}, function (res) {
      if (res.status == "success") { //获取猫的信息
        that.setData({ my_cat: res.mess });
      } else if (res.status == "error") {
        app.toast(res.mess)  //还未添加猫咪提示
      } else {
        app.modal("错误提示", "网络错误，是否重试？", function (re) {
          if (re) {
            that.onLoad(options)
          }
        })
      }
    })
  },
  onReady: function () {
  },
  onUnload: function () {  //界面卸载
    app.clear_overtime_order(); //删除所有未付款订单
  },
  onShow: function () {
    app.ispoint = 0;
    var openid = wx.getStorageSync('openid');
    that.setData({ level: app.data.person_msg_rr.level })
    that.setData({ over_money: app.data.person_msg_rr.credit2 })//会员卡剩余金额
    app.req("get_cat.html", { sessionid: wx.getStorageSync('3rd_session'), "openid": openid }, function (res) {
      if (res.status == "success") { //获取猫的信息
        that.setData({ my_cat: res.mess });
      } else if (res.status == "error") {
        app.toast(res.mess)//还未添加猫咪提示
      } else {
        app.modal("错误提示", "网络错误，是否重试？", function (re) {
          if (re) {
            that.onShow()
          }
        })
      }
    })
  },
  remarkInput:function(e){
    // console.log(e.detail.value)
    that.setData({remark:e.detail.value})
  },
  onHide: function () {
  },
  to_most_know:function(){
    wx.navigateTo({
      url: '../home/most_know'
    })
  },
  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({ index: e.detail.value, my_cat_care: [] }) 
    // console.log(e.detail.value + "  " + that.data.live_num);
    that.data.array2 = [];
    for (var i = 1; i <= (parseInt(e.detail.value)+1) * parseInt(that.data.live_num); i++) {
      that.data.array2.push(i + "只");
    }
    that.setData({ index2: 0, array2: that.data.array2, gg: true })
  },
  bindPickerChange2:function(e){
    this.setData({ index2: e.detail.value,gg2:true}) 
  },
  pay_money:function(e){   //点击确定预约弹出微信支付
    var openid = wx.getStorageSync('openid');
    var shop_id = wx.getStorageSync('shop_id');
    var userInfo = wx.getStorageSync('userInfo');
    if (!that.data.gg){app.toast_up('请选择房间数量！');return}
    if (!that.data.gg2) { app.toast_up('请选择猫咪数量！'); return }

    app.data.formid = e.detail.formId;
    if (userInfo.phone == '') {     //没有电话设置电话，有电话就返回
      wx.navigateTo({
        url: '../personal_mse/phone?op=op',
      }); return;
    }
  // console.log("s")
    if(!that.data.agree)
    {  app.toast_up("未同意协议"); return }
    // if (that.data.my_cat_care.length<=0)
    // { app.toast_up("未添加猫"); return; }
    // if (that.check_cat_num() == 2)  //检查猫的数量是否小于房间的数量
    // {app.toast_up("房间太多了");  return;}

    var catnum = that.data.array2[that.data.index2].substring(0, that.data.array2[that.data.index2].length - 1); //猫咪数量

    // console.log(that.data.my_cat_care);
    var cat_id=[]
    // for (var i = 0; i < that.data.my_cat_care.length;i++)
    // {
    //   cat_id.push(that.data.my_cat_care[i].id)
    // }
    var p=0;
    if (app.data.person_msg_rr.level>0)//如果是会员就用会员价
    {
      p = that.data.vip_price;
    }else{  
      p = that.data.house_price; 
    }
    that.setData({ adv_price: (parseInt(that.data.index) + 1) *p*that.data.d});
    var banjia = catnum - (parseInt(that.data.index) + 1); 
    if (banjia>0){
      that.setData({ adv_price: that.data.adv_price + 0.5 * banjia * p * that.data.d})
    }//同房间入住第二只猫咪半价
    console.log(parseInt(that.data.index) + 1)
   

    if (app.ispoint == 1) { return; } else { app.ispoint = 1; }//弹出支付框后就不允许执行了
    app.req("pay.html", { 'openid': openid, "start_time": that.data.startDate, "end_time": that.data.endDate, "roomtype": that.data.house_id, "roomnum": parseInt(that.data.index) + 1, "cat_id": cat_id, "catnum": parseInt(catnum),  "vs": app.data.vs,"price": that.data.adv_price,"remark":that.data.remark,"shop_id":shop_id},  //生成订单前后台先删除未付款订单
      function (res) {
       
        console.log(res);     //调用微信支付接口返回的信息
        if(res.status=="error"){//手慢房间被抢数量不足
          app.ispoint = 0;
          Show.alertShow(that, "info", res.mess)
          return;
        }
        that.setData({ pay_msg: res.mess});
        if (app.data.person_msg_rr.level > 0) {  //如果是会员，就会员支付
          that.util("open")
          return
        } else { that.wx_pay(); } //否则微信支付
        // that.setData({ actionSheetHidden: false })
      }, function (res) {
        app.ispoint = 0;
      });

  },
  ActionSheet_select: function ()//下方选项取消后即隐藏
  {
    this.setData({ actionSheetHidden_cat: true})
  },
  itemclick: function (e) {//点击选项时触发
    if (e.currentTarget.id == 2) {  //跳转到微信支付界面,   直接支付
      that.setData({ isclick_wx_pay: true })
      wx.setNavigationBarTitle({ title: '确认支付' })
    }
    if (e.currentTarget.id == 3)
    {  wx.navigateBack({  //点击取消返回上一界面
        delta: 1
      })
    }
    that.setData({ actionSheetHidden: true })
  },
  wx_pay:function(){     //微信确认支付
      wx.requestPayment(
        {
          'timeStamp': this.data.pay_msg.timeStamp,
          'nonceStr': this.data.pay_msg.nonceStr,
          'package': this.data.pay_msg.package,
          'signType': this.data.pay_msg.signType,
          'paySign': this.data.pay_msg.paySign,
          'success': function (res) {
            console.log(res)
            app.toast("支付成功！")
    
            setTimeout(function(){
              wx.redirectTo({
                url: '../advance/advance?ordersn=' + that.data.pay_msg.ordersn
              })
            },1000)
            app.orderSign(that.data.adv_price,"住房消费", that.data.pay_msg.ordersn);//发送微信模板消息
          },
          'fail': function (res) {
            app.ispoint = 0;
            app.toast_up("支付失败！")
            app.clear_overtime_order(); //支付失败删除所有过时订单
          },
          'complete': function (res) { }
        })

  },
  select_cat_show:function(){  //点击入住猫咪时下方出现选择自己的猫咪
    this.setData({ actionSheetHidden_cat: false })
  },
  select:function(e){
    // if (that.data.my_cat[e.currentTarget.id].czy == true) //通过改变此项数值设置选中属性
    // {
    //   that.data.my_cat[e.currentTarget.id].czy = false;
    //   that.setData({ my_cat:that.data.my_cat});
    // } else { 
    //   that.data.my_cat[e.currentTarget.id].czy = true;
    //    that.setData({ my_cat: that.data.my_cat }); 
    // }

    // console.log(that.data.my_cat_care)
    // console.log(that.data.my_cat[e.currentTarget.id])
    for (var i=0;i<that.data.my_cat_care.length;i++)
    {
      if (that.data.my_cat_care[i].id== that.data.my_cat[e.currentTarget.id].id)
        {
          app.toast_up("此猫已添加")   //还未添加猫咪提示
          return;
        }
    }
    if (that.check_cat_num()==1)  //检查猫的数量是否大于房间能入住的数量
    {
      app.toast_up("猫太多了")
      return;
    }
    
    that.data.my_cat_care.push(that.data.my_cat[e.currentTarget.id])
    that.setData({ my_cat_care: that.data.my_cat_care});//添加托养的猫咪
    that.setData({ actionSheetHidden_cat: true });
    // console.log(that.data.my_cat_care)
  },
  add_cat:function(){  //点击添加猫咪，跳转到添加猫咪界面
      wx.navigateTo({
        url: '../cat_mse/cat_mse',
      })
  },
  select_date:function(){  //点击调回选择日期
   wx.redirectTo({
     url: '../home/house_detail?startDate=' + this.data.startDate + '&endDate=' + this.data.endDate + "&house_id=" + that.data.house_id,
   })
    // wx.navigateBack({ delta: 1 })
  },
  delete_cat:function(e){//移除准备托养的猫咪
    this.data.my_cat_care.splice(e.currentTarget.dataset.idx, 1);
    that.setData({ my_cat_care: that.data.my_cat_care});
  },
  get_room_num:function( sd, ed, hd){  //获取日期范围内该类房间的剩余数量
    app.req("get_room_num.html", { 'start_time':sd, "end_time": ed, "type": hd,"shop_id":wx.getStorageSync('shop_id')},
      function (res) {
        that.data.array=[];
        for (var i = 1; i <= res.mess;i++)
        { that.data.array.push(i+"间"); }   
        that.setData({ array: that.data.array})
        
        that.data.array2 = [];
        for (var i = 1; i <= 1* parseInt(that.data.live_num); i++) {
          that.data.array2.push(i + "只");
        }
        that.setData({ index2: 0, array2: that.data.array2 })

      }, function (res) {
        // console.log(res);
      });
  },
  set_house_msg:function(h_id){
    for (var i = 0; i < app.hotelData.house_type.length;i++)
      {
      if (app.hotelData.house_type[i].id==h_id)
        {
          // console.log(app.hotelData.house_type[i]);
          var h1 = app.hotelData.house_type[i].name;
          var h2 = app.hotelData.house_type[i].price;
          var h3 = app.hotelData.house_type[i].live_num;
          var h4 = app.hotelData.house_type[i].vip_price;
          that.setData({ house_name: h1, house_price: h2, vip_price: h4,live_num:h3})
        }
      }
  },
  check_cat_num:function(){//检查房间数和猫的数量
    // console.log(that.data.live_num * (parseInt(that.data.index) + 1))
    var re = that.data.array2[that.data.index2].substring(0, that.data.array2[that.data.index2].length-1)
    // console.log(re)
    if (that.data.live_num * (parseInt(that.data.index) + 1) <= parseInt(re))
    {
      return 1;
    }
    if ((parseInt(that.data.index) + 1) > parseInt(re)) {
      return 2;
    }
    return 3;
  },
  agreeChange:function(e){
    // console.log(that.data.agree)
    that.setData({ agree: !that.data.agree });
    // var agree = e.detail.value.length
    // if (agree == 1) {
    //   that.data.agree = true
    // } else {
    //   that.data.agree = false
    // }
  },
  input_pwd: function (e) {//会员支付
    var openid = wx.getStorageSync('openid');
    that.setData({ pwd: e.detail.value.trim() })
    if (that.data.pwd.length == 6 && app.data.pointed==true ) { //密码位数够了就判断
      that.setData({ focus:false})
      app.data.pointed=false;   //避免快速点击调用两次方法
      setTimeout(function () { app.data.pointed = true; }, 1500)

    
      app.req("pay_from_member.html", { "ordersn":that.data.pay_msg.ordersn,"price": that.data.adv_price, "pwd": that.data.pwd, "type": 'home', "openid": openid,'shop_id':wx.getStorageSync('shop_id') }, function (res) {
        if (res.status == "success") {
          console.log(666)
          app.toast(res.mess)
          that.util('close')//关闭支付弹窗，可以隐藏不关也可
          
          app.get_msg_rr();  //充值成功后刷新个人在人人商城的信息
          setTimeout(function () {
            wx.redirectTo({
              url: '../my_care/adv_success?ordersn=' + that.data.pay_msg.ordersn
            })
          }, 1000)
          app.orderSign(that.data.adv_price, "住房消费", that.data.pay_msg.ordersn);//发送微信模板消息
        } else if (res.status == "error") {
          app.ispoint = 0;
          console.log(res)
          wx.showToast({
            title: res.mess,
            image: '../../images/g.png',
            duration: 1500
          })
          // app.toast_up(res.mess);
          that.setData({ pwd: '' })
        } else {
          app.ispoint = 0;
          app.modal("错误提示", "网络错误，是否重试？", function (re) {
            if (re) {
              that.input_pwd(e)
            }
          })
        }
      })
    }
  },
  cle: function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  to_care_agree:function(){//点击双方寄养协议跳到协议界面
    // app.toast_up("跳到双方协议界面");
    this.setData({
      showModal: true
    })    
  },
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },
 

  util: function (currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例 
    var animation = wx.createAnimation({
      duration: 200, //动画时长 
      timingFunction: "linear", //线性 
      delay: 0 //0则不延迟 
    });
    // 第2步：这个动画实例赋给当前的动画实例 
    this.animation = animation;
    // 第3步：执行第一组动画 
    animation.opacity(0).rotateX(-100).step();
    // 第4步：导出动画对象赋给数据对象储存 
    this.setData({
      animationData: animation.export()
    })
    // 第5步：设置定时器到指定时候后，执行第二组动画 
    setTimeout(function () {
      // 执行第二组动画 
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象 
      this.setData({
        animationData: animation
      })
      //关闭 
      if (currentStatu == "close") {
        app.ispoint = 0;
        that.setData({ focus: false });
        app.clear_overtime_order(); //，支付失败删除所有过时订单,
        this.setData( { showModalStatus: false }
        );
      }
    }.bind(this), 200)
    // 显示 
    if (currentStatu == "open") {
      this.setData({showModalStatus: true});
      setTimeout(function () {
        that.setData({ focus: true });//出现输入密码时获取焦点
      },550);
     
    }
  },
  preventTouchMove: function () { },//有用，不能删
})